<script setup>
import {
    Edit,
    Delete,
    Search,
    Download
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import {sportsPageService} from '@/api/sportsProject/sportsProject.js'
import {getSelectListService} from '@/api/sportsProject/sportsProject.js'
import {getProjetcInfo} from '@/api/sportsProject/sportsProject.js'
import {deleteProjectService,exportPageService} from '@/api/sportsProject/sportsProject.js'
import {updateProjectService} from '@/api/sportsProject/sportsProject.js'
//导入消息框
import {ElMessage,ElMessageBox} from 'element-plus'
//导入token状态
import { useTokenStore } from '@/stores/token.js'
//调用useTokenStore得到状态
const tokenStore = useTokenStore();
//分页条数据模型
const currentPage = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(6)//每页条数
//用户搜索时选中的分类id
const sportsName=ref()
//接受回显数据模型
const sportsPage=ref();
//创建学期
const select = ref([])
//学期
//弹窗标题
const title=ref('')
//控制添加分类弹窗
const dialogVisible = ref(false)
const year = ref(null)
const loading = ref(true)
const getSportsPage = async () => {
    const getSportsProjectPageModel = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    sportsName: sportsName.value ? sportsName.value: null,
    yearTermID:year.value ? year.value:null
    }
    let result = await sportsPageService(getSportsProjectPageModel);
    //渲染列表数据
    sportsPage.value = result.data.records;
    total.value=result.data.total;
    loading.value=false
}
const getSelectList =async () =>{
    let result = await getSelectListService();
    //渲染下拉框数据
    select.value = result.data;
    year.value=select.value[1].yearTermID
    getSportsPage()
}
getSelectList()
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getSportsPage()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    currentPage.value = num
    getSportsPage()
}
const check=()=>{
    getSportsPage()
}
const input=()=>{
    year.value=null
    getSportsPage()
}
const getInfo=ref({
    sportsID:""
})
//添加or修改项目分类数据模型
const project = ref({
    sportsID:"",
    sportsName:"",
    yearTermID:"",
    sportsMemo:"",
    fileLsit:[],
    fileUrl:'',
    fileName:''
})
const list=ref()
const updateChange=async (row)=>{
    project.value.sportsID=""
    title.value = '修改项目信息'
    dialogVisible.value = true
    getInfo.value.sportsID=row.sportsID
    let result = await getProjetcInfo(getInfo.value)
    project.value=result.data
    list.value=project.value.fileList?project.value.fileList:[]
}
const addProject=async()=>{

}
const updateProjectByID=async()=>{
    let result = await updateProjectService(project.value);
    ElMessage.success(result.data? result.data:'修改成功')
    //隐藏弹窗
    dialogVisible.value = false
    //再次访问后台接口，查询所有分类
    getSportsPage()
}
const deletProjectByID=async(row)=>{
    ElMessageBox.confirm(
        '你确认删除项目ID为：'+row.sportsID+'的项目信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(async () => {
            //用户点击了确认
            getInfo.value.sportsID=row.sportsID
            let result = await deleteProjectService(getInfo.value)
            ElMessage.success("删除成功！");
            //再次调用 getSportsPage()，获取所有项目
            getSportsPage()
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
const exportClick=async ()=>{
    ElMessageBox.confirm(
        '确认导出项目信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then( () => {
            //用户点击了确认
            exportExcel()
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//文件上传成功的回调函数
const uploadSuccess = (result)=>{
    ElMessage.success("上传成功！")
    project.value.fileList=list.value?list:[]
    project.value.fileUrl=result.data
    project.value.fileName=list.value[0].name
}
const uploadError=(result)=>{
    ElMessage.success("上传失败！")
}
const look=(result)=>{
    ElMessage.success("上传失败！")
}
const exportExcel=async()=>{
    const model = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    sportsName: sportsName.value ? sportsName.value: null,
    yearTermID:year.value ? year.value:null
    }
    try {
    let blob=await exportPageService(model)
    const date = new Date();
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    const currentTime = `${hours}:${minutes}:${seconds}`;
    const decodedFileName = '运动会项目'+currentTime
    const downloadLink = document.createElement('a')
    downloadLink.href = URL.createObjectURL(blob)
    downloadLink.download = decodedFileName
    downloadLink.click()
    URL.revokeObjectURL(downloadLink.href)
    ElMessage.success("导出成功！")
        // let res=await exportPageService(model)
        // if(res){
        //     const elink = document.createElement('a');
        //     elink.download = '文件名称.xls';
        //     elink.style.display = 'none';
        //     const blob = new Blob([res], { type: 'application/x-msdownload' });
        //     elink.href = URL.createObjectURL(blob);
        //     document.body.appendChild(elink);
        //     elink.click();
        //     document.body.removeChild(elink);
        //   }else {
        //     this.$message.error('导出异常请联系管理员');
        //   }
        } catch (error) {
          console.log(error);
          ElMessage.error('导出异常请联系管理员');
        }
}
const rules = {
    sportsName: [
        { required: true, message: '请输入项目名！', trigger: 'blur' },]
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span><strong>运动会比赛项目信息</strong></span>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="创建学期" style="width: 300px;">
                <el-select v-model="year" class="m-2" placeholder="全部"  @change="check">
                <el-option
                        v-for="item in select"
                        :key="item.yearTermID"
                        :label="item.yearTermName"
                        :value="item.yearTermID"
                />
            </el-select>
            </el-form-item>
            <el-form-item label="项目名(模糊查询)">
                <el-input placeholder="请输入项目名" v-model="sportsName" :suffix-icon="Search"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"@click="input">搜索</el-button>
                <el-button @click="sportsName='',year=null,getSportsPage()">重置</el-button>
            </el-form-item>
            <el-form-item style="margin-left: 200px;">
                <el-button type="primary"@click="exportClick()">
                    导出Excel<el-icon><Download /></el-icon>
                </el-button>
            </el-form-item>
        </el-form>
        <!-- 比赛项目列表 -->
        <el-table  v-loading="loading"
                element-loading-text="Loading..."
                :element-loading-spinner="svg"
                element-loading-svg-view-box="-10, -10, 50, 50"
                :data="sportsPage" style="width: 100%">
                <el-table-column type="selection" width="55" />
            <el-table-column label="项目编号" prop="sportsID" width="100%"></el-table-column>
            <el-table-column label="项目名称" prop="sportsName" show-overflow-tooltip effect="light"> </el-table-column>
            <el-table-column label="项目类型">
                <template #default="{ row }">
                    <el-text class="mx-1" type="primary"v-if="row.type ===1">单人项目</el-text>
                    <el-text class="mx-1" type="warning"v-else>团队项目</el-text>
                 </template>
            </el-table-column>
            <el-table-column label="创建学期" prop="yearTermID"width="100%"></el-table-column>
            <el-table-column label="最后修改时间" prop="lastDate"show-overflow-tooltip></el-table-column>
            <el-table-column label="修改者" prop="operator"></el-table-column>
            <el-table-column label="相关附件" prop="fileName"show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-tooltip content="点击下载" effect="light">
                    <el-link type="primary" :href="row.fileUrl" target="_blank" :download="row.fileName"
                    :underline="false">
                        {{ row.fileUrl?row.fileName:"" }}
                    </el-link>
                        </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="sportsMemo"width="200"show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click=updateChange(row)></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click=deletProjectByID(row)></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="未查找到数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[6, 8 ,10]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    </el-card>
    <!-- 添加或修改时弹窗 -->
<el-dialog v-model="dialogVisible" :title="title" width="35%":rules="rules">
    <el-form v-model="project" status-icon class="demo-ruleForm">
        <el-form-item label="项目编号:" prop="sportsID"label-width="75px">
            <el-input v-model="project.sportsID" disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="创建学期:" prop="yearTermID"label-width="75px">
            <el-input v-model="project.yearTermID"disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="项目名称:" prop="sportsName"label-width="75px">
            <el-input v-model="project.sportsName" minlength="1" maxlength="15"></el-input>
        </el-form-item>
        <el-form-item label="备注:" prop="sportsMemo"label-width="75px">
            <el-input v-model="project.sportsMemo" type="textarea" maxlength="150"
            show-word-limit autosize></el-input>
        </el-form-item>
        <el-form-item label="相关附件:" prop="fileUrl">
            <el-upload
        v-model:file-list="list"
        class="upload-demo"
        action="../api/upload"
        multiple
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :headers="{'Authorization':tokenStore.token}"
        :limit="1"
        :on-preview="look"
        accept=".pdf"
  >
    <el-button type="primary">选择文件</el-button>
    <template #tip>
      <div class="el-upload__tip">
        仅允许上传一个文件,仅限pdf格式
      </div>
    </template>
  </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="title==='添加项目'? addProject():updateProjectByID()"> 确认 </el-button>
            </span>
    </template>
</el-dialog>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>